package bd403.UIComponents;

import java.text.DecimalFormat;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import bd403.Backend.Drink;
import bd403.Backend.DrinkParams;
import bd403.Backend.DrinkStorage;
import bd403.namespace.BDActivity;
import bd403.namespace.R;
import bd403.utils.KeyboardSetup;

/* UI and functionality for an Individual drink page. This page displays information about a specific
 * drink including its name and rating. It also displays reviews for the drink. From this page users
 * can add a review for the drink, or add this drink to their favorites.
 * Main author: Joseph
 */

public class AddReviewActiv extends Activity {
    private Drink currentDrink;
    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.addreview);
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        // Get the current Drink that's being viewed
        DrinkStorage ds = BDActivity.getStorage();
        currentDrink = ds.getCurrentDrink();
        initRatingBar();
        
        // Initialize reviews to display to the user
        setDrinkText(currentDrink);
        setupKeyboard();
        setupSubmitListener();
    }
    
    /* Sets up the options menu for AddReviewActiv.
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(getString(R.string.title_help));
		return true;
    }
	
	/* Launches the Help page once it is clicked from the options menu.
	 */
	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
		Intent i = new Intent(this, HelpActiv.class);
        startActivity(i);
        return true;
    }

    /* Sets the info for the current drink the user is viewing
     */
    private void setDrinkText(Drink d) {
        TextView drinkTitle = (TextView) findViewById(R.id.view_drinktitle);
        TextView drinkRating = (TextView) findViewById(R.id.view_drinkrating);
        ImageView iv = (ImageView) findViewById(R.id.icon);

        drinkTitle.setText(d.getName());
        DecimalFormat f = new DecimalFormat(getString(R.string.numberformat_rating));
        drinkRating.setText(getString(R.string.prompt_rating) + f.format(d.getRating()));
        
        if (iv != null) {
            switch(d.getType()) {
            case 0 : 
                iv.setImageResource(R.drawable.beer_icon);
                break;
            case 1 :
                iv.setImageResource(R.drawable.wine);
                break;
            case 2 :
                iv.setImageResource(R.drawable.cocktail);
                break;
            default :
                iv.setImageResource(R.drawable.default_icon);
            }
        }
    }

    /* Sets up the initial rating on the rating bar and forces only full starts to be
     * accepted.
     */
    private void initRatingBar() {
        /* Initialize the rating bar */
        final RatingBar ratingbar = (RatingBar) findViewById(R.id.ratingBar);
        ratingbar.setRating(3);
        ratingbar.setStepSize((float) 1.0);
    }

    /* Sets up the soft keyboard to minimize on a 'Return' key click.
	 */
    private void setupKeyboard() {
        final EditText commentText = (EditText) findViewById(R.id.commentText);

        // Changes enter key on soft keyboard to minimize keyboard
        KeyboardSetup ks = KeyboardSetup.getInstance(this);
        ks.setupKeyboard(commentText);
    }


    /* Initializes the onClick listener for the '+ Add Review' button.
     */
    private void setupSubmitListener() {
        final EditText commentText = (EditText) findViewById(R.id.commentText);
        final RatingBar ratingbar = (RatingBar) findViewById(R.id.ratingBar);

        /* Set up the listener for a drink submission */
        Button addReview = (Button) findViewById(R.id.submitReview);
        addReview.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
            	
            	String comment = commentText.getText().toString().trim();
            	if (!validChar(comment.toLowerCase())) {
            		Toast.makeText(getApplicationContext(), getString(R.string.toast_review_invalid), Toast.LENGTH_SHORT).show();
            	} else {
	                Intent intent = new Intent();
	                setResult(RESULT_OK, intent);
	
	                /* Pull the drink information from the form */
	                int rating = (int) ratingbar.getRating();
	                int type = currentDrink.getType();
	                String drinkType = getString(R.string.radiolabel_beer);
	                if (type == 1) {
	                    drinkType = getString(R.string.radiolabel_wine);
	                } else if (type == 2) {
	                    drinkType = getString(R.string.radiolabel_mixed);
	                }    
	                DrinkParams dp = new DrinkParams(currentDrink.getName(), comment, rating, drinkType);
	
	                // Attempt to add a new review under existing drink to the App
	                DrinkStorage ds = BDActivity.getStorage();
	               	if (!ds.addReview(dp)) {
	               		Toast.makeText(getApplicationContext(), getString(R.string.toast_review_error), Toast.LENGTH_SHORT).show();
	               	} else {
	               		startActivity(new Intent(getApplicationContext(), DrinkViewActiv.class));
	               		finish();
	               		Toast.makeText(getApplicationContext(), getString(R.string.toast_review_success) , Toast.LENGTH_SHORT).show();
	               	}
            	}
            } 
        });
    }
    
    /* Returns true if this input String contains all legal characters. Otherwise returns false.
	 * Legal characters for a comment include all alphabetic characters, spaces, exclamation,
	 * and period.
	 */
	private boolean validChar(String input) {
		// a = 97, z = 122
		for (int i = 0; i < input.length(); i++) {
			if (input.charAt(i) < 'a' || input.charAt(i) > 'z') {
				if (input.charAt(i) != ' ' && input.charAt(i) != '!' && input.charAt(i) != '.') {
					return false;
				}
			}
		}
		return true;
	}
}
